<template>
  <div id="login">
    <div id="head">
      <div class="headerImg">
        <img class="logo" src="../assets/logo.png" />
        <span>{{ localInfo.hospitalName }}</span>
      </div>
      <div class="headerVersion">版本号:2.103.135</div>
    </div>
    <div id="body">
      <div class="bodyLeftTitle">
        <span>欢迎进入{{ localInfo.systemName }}</span>
      </div>
      <div class="bodyForm">
        <el-tabs type="card" class="demo-tabs" v-model="activeName" @tab-click="getCALogin">
          <el-tab-pane label="账号登录" name="first" v-if="logType==1||logType==''">
            <div class="FormBody">
              <el-form ref="ruleFormRef" :rules="loginRule" :model="loginForm" size="large" class="formInput">
                <el-form-item prop="username">
                  <el-input ref="loginRef" id="userNameInputs" v-model="loginForm.username" type="text" prefix-icon="User" @blur="handleMouseMove" placeholder="请输入用户代号" @keyup.enter="keyupEnter"></el-input>
                </el-form-item>
                <el-form-item prop="realname">
                  <el-input ref="codeRef" disabled v-model="loginForm.realname" type="text" prefix-icon="Avatar" placeholder="用户名称"></el-input>
                </el-form-item>
                <el-form-item prop="orgName">
                  <el-input ref="codeRef" disabled v-model="loginForm.orgName" type="text" prefix-icon="Histogram" placeholder="机构名称"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="loginForm.password" type="password" ref="inputPasswordRef" prefix-icon="Unlock" show-password placeholder="请输入密码" autocomplete="new-password" @keyup.enter="onEnter"></el-input>
                </el-form-item>
                <!-- <el-form-item prop="verifyCode" style="margin-bottom:15px;" class="input-s">
            <el-input
              v-model="loginForm.verifyCode"
              type="text"
              placeholder="请输入验证码"
              @keyup.enter="onEnter"
            >
              <i  class="el-icon-picture-outline-round"></i>
            </el-input>
            <div class="div-vcode" @click="getVerificationCode()">
              <img :src="loginForm.verifyCodeImg" />
            </div>
          </el-form-item>
          <el-form-item prop="keyId" v-show="false">
            <el-input v-model="loginForm.keyId" type="text" >
            </el-input>
            </el-form-item>-->

                <el-form-item>
                  <el-checkbox v-model="loginForm.remPwd">记住密码</el-checkbox>
                  <el-link type="primary" :underline="false" style="float: right; display: none">忘记密码？</el-link>
                </el-form-item>
                <el-form-item style="margin-bottom: 15px; line-height: 20px" v-if="loginForm.error !== ''">
                  <el-alert :title="loginForm.error" type="error" style="line-height: 20px" @close="loginForm.error = ''" show-icon></el-alert>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :loading="loading" class="loginButton" @click="login(ruleFormRef)">登&nbsp;&nbsp;&nbsp;&nbsp;录</el-button>
                </el-form-item>
              </el-form>
              <el-button type="primary" style="display: none" @click="login">logout</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane v-if="(!IsEmpty(caType))&&(logType==2||logType=='')" label="CA登录" name="thrid">
            <div class="FormBody">
              <CaLogin v-if="caType === '1'" @yfCALoginCheck="yfCALoginCheck"></CaLogin>
              <SdCaLogin ref="sdCaLoginRef" v-if="caType === '2'" @SdCALoginCheck="SdCALoginCheck"></SdCaLogin>
              <div class="qrcodeDiv" v-if="caType === '3'">
                <div id="qrcode" class="qrcode"></div>
                <div class="qrcodeOutTimeDiv">
                  <div>二维码过期时间:</div>
                  <div class="outTime">{{timeCount}}</div>
                  <vxe-button type="text" icon="vxe-icon-refresh" content="刷新" @click="CALogin"></vxe-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <div id="foot">
      <!-- <span>COPYRIGHT ©2023-2024 医顺达（山东）信息技术有限公司 版权所有 保留一切权利</span> -->
      <span>{{localInfo.companyName}}</span>
      <span>服务热线：{{ localInfo.companyTel }}</span>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, toRefs } from 'vue';
import { AppStore } from '../stores/store';
import type { FormInstance, FormRules, ElInput } from 'element-plus';
import { Encrypt } from '../utils/crypto';
import { VxeMessage, VxeNotifyType } from '../utils/CommonMessage';
import { IsEmpty, notifyType, notifyMessage } from '@/utils/common';
import { GetGolbalOptions, GetLocalOptions, getOptionValueByCodeGlobalOption } from '@/utils/SysOptionsHelper';
import QRCode from 'qrcodejs2-fix';
import SdCaLogin from '@/components/SdCaLogin.vue';
import CaLogin from '@/components/CaLogin.vue';

// 全局变量定义区 ==========
const { proxy }: any = getCurrentInstance();
const store = AppStore();

let syxxList: any = reactive([]); //选择字典(医院/系统名/公司名/公司电话)
let localInfo: any = reactive([]); //当前用户信息(医院/系统名/公司名/公司电话)
const ruleFormRef = ref<FormInstance>();
let loginRef = ref<InstanceType<typeof ElInput>>();
let loading = ref(false);
let activeName = ref('first');
let signDataId = ref(null);
let timerId = ref(null);
let sdCaLoginRef = ref(null);
let caType = window.apiUrl.CA_TYPE;
let logType = ref('');
let loginForm = reactive({
  username: '',
  password: '',
  remPwd: false,
  realname: '',
  orgName: '',
  error: '',
  verifyCode: '',
  verifyCodeImg: '',
  keyId: ''
});

let loginRule = reactive<FormRules>({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    {
      min: 3,
      max: 20,
      message: '长度为6到20个字符',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 20,
      message: '长度为3到20个字符',
      trigger: 'blur'
    }
  ]
});

// 方法定义区 =============
onMounted(() => {
  // getVerificationCode();
  //加载系统选项
  GetGolbalOptions();
  GetLocalOptions();
  getDictItemsList(); //批量获取字典

  //登录方式（伊通），1为普通用户登录，2为CA登录，空为全部登录
  proxy.$http
    .get(`/api/sys/sysParamValue/findSysParamFieldAndValueByCode`, {
      params: { paramCode: 'xtxxcs', field: 'logbytypecaoruser' }
    })
    .then((res: any) => {
      if (res && res.status && res.status.code && res.status.code === 1) {
        if (res.data[0]) {
          logType.value = res.data[0].value;
        }
        if (logType.value == 2) {
          activeName.value = 'thrid';
        } else {
          activeName.value = 'first';
        }
        const data = {
          paneName: activeName.value
        };
        getCALogin(data);
      }
    })
    .catch((err) => {
      console.log('系统选项报错', err);
    });
});

function getCALogin(tab) {
  if (tab.paneName == 'thrid' && caType == '3') {
    CALogin();
  } else {
    if (timerId.value) {
      clearInterval(timerId.value);
    }
    if (tab.paneName == 'thrid' && caType == '2') {
      let $Xtable = proxy.$refs.sdCaLoginRef;
      if ($Xtable) {
        $Xtable.getcert();
      }
    }
  }
}

function CALogin() {
  timeCount.value = 60;
  clearInterval(timerId.value);
  const url = '/public/user/getCAScanCode';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      if (res.data) {
        signDataId.value = res.data.signDataId;
        document.getElementById('qrcode').innerHTML = '';
        proxy.$nextTick(() => {
          new QRCode(document.getElementById('qrcode'), {
            text: res.data.qrCode,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff'
          });
          timerId.value = setInterval(checkIsScan, 1000);
        });
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function SdCALoginCheck(data: any) {
  console.log('@@@@@@@@@@@' + data.username);
  console.log('###########' + data.certId);
  sessionStorage.setItem('sdCertId', data.certId);
  const url = '/public/user/sdcaLogin';
  let obj = {
    username: data.username,
    base64Image: data.base64Image
  };

  proxy.$http
    //注意此处的数据条数
    .post(url, obj)
    .then((res: any) => {
      if (res.data) {
        clearInterval(timerId.value);
        store.setToken(res.data.token);
        const user: any = {
          id: res.data.user.id,
          hisEmployeeCode: res.data.user.hisEmployeeCode,
          realname: res.data.user.realname,
          tel: res.data.user.tel,
          username: res.data.user.username,
          orgId: res.data.user.orgId,
          //role:res.data.user.UserRoles[0].roleId,
          orgName: res.data.user.organization ? res.data.user.organization.name : '',
          orgCode: res.data.user.organization ? res.data.user.organization.code : '',
          orgType: res.data.user.organization ? res.data.user.organization.type : '',
          layoutSkin: res.data.user.layoutSkin,
          systemList: res.data.user.SystemList,
          orgList: res.data.user.orgList,
          signDataId: signDataId.value,
          caUserId: res.data.user.caUserId
        };
        VxeMessage('登录成功', VxeNotifyType.success);
        timeCount.value = 0;
        store.setUserInfo(user);
        finPermissionObj();
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function yfCALoginCheck(data: any) {
  const url = '/public/user/yfcaLogin';
  let obj = {
    caUserId: data.sn
  };

  proxy.$http
    //注意此处的数据条数
    .post(url, obj)
    .then((res: any) => {
      if (res.data) {
        clearInterval(timerId.value);
        store.setToken(res.data.token);
        const user: any = {
          id: res.data.user.id,
          hisEmployeeCode: res.data.user.hisEmployeeCode,
          realname: res.data.user.realname,
          tel: res.data.user.tel,
          username: res.data.user.username,
          orgId: res.data.user.orgId,
          //role:res.data.user.UserRoles[0].roleId,
          orgName: res.data.user.organization ? res.data.user.organization.name : '',
          orgCode: res.data.user.organization ? res.data.user.organization.code : '',
          orgType: res.data.user.organization ? res.data.user.organization.type : '',
          layoutSkin: res.data.user.layoutSkin,
          systemList: res.data.user.SystemList,
          orgList: res.data.user.orgList,
          signDataId: signDataId.value,
          caUserId: res.data.user.caUserId
        };
        VxeMessage('登录成功', VxeNotifyType.success);
        timeCount.value = 0;
        store.setUserInfo(user);
        finPermissionObj();
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

let timeCount = ref(60);
function checkIsScan() {
  timeCount.value--;
  const url = '/public/user/checkIsScan';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { signDataId: signDataId.value }
    })
    .then((res: any) => {
      if (res.data) {
        clearInterval(timerId.value);
        store.setToken(res.data.token);
        const user: any = {
          id: res.data.user.id,
          hisEmployeeCode: res.data.user.hisEmployeeCode,
          realname: res.data.user.realname,
          tel: res.data.user.tel,
          username: res.data.user.username,
          orgId: res.data.user.orgId,
          //role:res.data.user.UserRoles[0].roleId,
          orgName: res.data.user.organization ? res.data.user.organization.name : '',
          orgCode: res.data.user.organization ? res.data.user.organization.code : '',
          orgType: res.data.user.organization ? res.data.user.organization.type : '',
          layoutSkin: res.data.user.layoutSkin,
          systemList: res.data.user.SystemList,
          orgList: res.data.user.orgList,
          signDataId: signDataId.value,
          caUserId: res.data.user.caUserId
        };
        VxeMessage('登录成功', VxeNotifyType.success);
        timeCount.value = 0;
        store.setUserInfo(user);
        finPermissionObj();
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
  if (timeCount.value < 1 && timerId.value) {
    clearInterval(timerId.value);
  }
}

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['SYHYXX'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'SYHYXX');
  syxxList.push(...horizontalType.detailDataList);
  let localInfoItemValue = syxxList.find((item) => item.code === '001');
  Object.assign(localInfo, localInfoItemValue);
}

// 获取验证码
// async function  getVerificationCode() {
//     const url = '/public/user/getVerificationCode';
//     proxy.$http
//       .get(url)
//       .then((res: any) => {
//         if (res.status.code !== 1) {
//           VxeMessage(res.status.msg, VxeNotifyType.warning);
//         } else {
//           loginForm.verifyCodeImg = 'data:image/jpeg;base64,' + res.data.verifyImage;
//           loginForm.keyId = res.data.keyId;
//           loginForm.verifyCode = '';
//         }
//         loading.value = false;
//       })
//       .catch((err: string) => {
//         loading.value = false;
//         VxeMessage(err,VxeNotifyType.error)
//       });
// };

// 用户代号输入框回车事件
function keyupEnter(e: any) {
  const key = e.which || e.keyCode;
  if (key === 13) {
    proxy.$refs.inputPasswordRef.focus();
  }
}

//密码输入框回车事件
function onEnter(e: any) {
  const key = e.which || e.keyCode;
  if (key === 13) {
    login(ruleFormRef.value);
  }
}

onMounted(() => {
  if (store.remUser && store.remUser.remPwd) {
    loginForm.username = store.remUser.username;
    loginForm.password = store.remUser.password;
    loginForm.remPwd = store.remUser.remPwd;
  } else {
    loginRef.value!.focus();
  }
  handleMouseMove(); //调接口回显用户名称和机构名称
});

// 鼠标移出事件(显示用户名称和机构名称)
function handleMouseMove() {
  if (!IsEmpty(loginForm.username)) {
    const url = '/public/user/getUserName/' + loginForm.username;
    proxy.$http
      //注意此处的数据条数
      .get(url)
      .then((res: any) => {
        if (res.data) {
          loginForm.realname = res.data.realname;
          loginForm.orgName = res.data.orgName;
        }
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}

//登录
function login(formRef: any) {
  loading.value = true;
  loginForm.error = '';
  formRef.validate((valid: any) => {
    if (!valid) {
      loading.value = false;
      return false;
    }
    const url = '/public/user/login';
    proxy.$http
      .post(url, {
        username: loginForm.username,
        password: loginForm.password,
        verifyCode: loginForm.verifyCode,
        keyId: loginForm.keyId
      })
      .then((res: any) => {
        if (res.status.code === 1) {
          store.setToken(res.data.token);
          const user: any = {
            id: res.data.user.id,
            hisEmployeeCode: res.data.user.hisEmployeeCode,
            realname: res.data.user.realname,
            tel: res.data.user.tel,
            username: res.data.user.username,
            orgId: res.data.user.orgId,
            //role:res.data.user.UserRoles[0].roleId,
            orgName: res.data.user.organization ? res.data.user.organization.name : '',
            orgCode: res.data.user.organization ? res.data.user.organization.code : '',
            orgType: res.data.user.organization ? res.data.user.organization.type : '',
            layoutSkin: res.data.user.layoutSkin,
            systemList: res.data.user.SystemList,
            orgList: res.data.user.orgList
          };
          VxeMessage('登录成功', VxeNotifyType.success);
          store.setUserInfo(user);
          //缓存保存用户名密码
          if (loginForm.remPwd) {
            store.setRemUser({
              username: loginForm.username,
              password: loginForm.password,
              remPwd: true
            });
          } else {
            store.setRemUser({
              username: '',
              password: '',
              remPwd: false
            });
          }
          finPermissionObj();
        } else {
          loginForm.error = res.status.msg;
        }
        loading.value = false;
      })
      .catch((err: string) => {
        loading.value = false;
        VxeMessage(err, VxeNotifyType.warning);
      });
    return true;
  });
}
function finPermissionObj() {
  proxy.$http
    .get('/api/user/sysUserAuthDetail/getLoginUserAuthMapByUserId', {
      params: {
        userId: store.userInfo.id
      }
    })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
        return;
      }

      if (!IsEmpty(res.data.modules)) {
        //先找是否有主模块
        const roleOBJLogin = res.data.modules.find((p) => !IsEmpty(p.baseModule) && p.baseModule);
        if (!IsEmpty(roleOBJLogin)) {
          localStorage.setItem('logBaseUrl', roleOBJLogin.baseUrl);
          localStorage.setItem('moduleId', roleOBJLogin.id);
        } else {
          const roleOBJ = res.data.modules.find((p) => p.code == '002');
          if (!IsEmpty(roleOBJ)) {
            localStorage.setItem('logBaseUrl', roleOBJ.baseUrl);
            localStorage.setItem('moduleId', roleOBJ.id);
          } else {
            const roleOBJ = res.data.modules[0];            
            localStorage.setItem('logBaseUrl', roleOBJ.baseUrl);
            localStorage.setItem('moduleId', roleOBJ.id);
          }
        }
      }

      store.setRoleModel(res.data.modules);
      store.setModuleMenuMap(res.data.moduleMenuMap);
      store.setModulePointMap(res.data.modulePointCodeMap);
      store.setRptGroupList(res.data.rptGroupList);
      store.setInstrSetupList(res.data.instrSetupList);
      store.setRole(res.data.sysRoles);
      //东北双塔区人民医院要求护士登录跳转条码打印页面，2025-03-26，如有问题请添加系统参数控制
      if (res.data.sysRoles && res.data.sysRoles.length > 0 && (res.data.sysRoles[0].id == '1712001650775232516' || res.data.sysRoles[0].id == '1864518190229278721')) {
        localStorage.setItem('moduleId', '1747828187831173122');
        proxy.$router.push('/printBarcode');
      } else {
        proxy.$router.push('/');
      }
    })
    .catch((err: string) => {
      console.log(err);

      notifyMessage(err, notifyType.warning, proxy);
    });
}
</script>
<style lang="scss" scoped>
#login {
  height: 100%;
  width: 100%;
  background-image: url('../assets/images/login_bg_new.jpg');
  background-size: cover;
  position: fixed;
  overflow: hidden;

  #head {
    width: calc(100% - 3%);
    height: 5%;
    padding: 1% 1.5%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .headerImg {
      height: 100%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;

      .logo {
        height: 40px;
        width: 40px;
      }

      span {
        color: $base-white;
        font-size: 30px;
        font-weight: 400;
        margin-left: 15px;
      }
    }

    .headerVersion {
      color: #fff;
      font-size: 14px;
    }
  }

  #body {
    height: 65%;
    margin: 2.5% 15%;
    width: calc(100% - 30%);
    background-image: url('../assets/images/login_bg_div.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    .bodyLeftTitle {
      position: relative;
      float: left;
      width: 64%;
      height: 100%;
      span {
        color: $base-white;
        font-size: 30px;
        font-weight: 500;
        position: absolute;
        left: 33%;
        top: 6%;
        // padding: 3% 16%;
      }
    }

    .bodyForm {
      float: right;
      width: calc(35% + 5px);
      height: 100%;
      ::v-deep .el-tabs__header .el-tabs__item.is-active {
        background-color: #fff;
        color: #60cde7;
      }
      ::v-deep .el-tabs__header .el-tabs__item:hover {
        color: #007199;
      }

      .FormBody {
        width: 100%;
        height: 85%;
        .formInput {
          padding: 45px 90px;
          .el-input {
            width: 288px;
            :deep(.el-input__wrapper) {
              border-radius: 10px;
            }
          }

          // 复选框选中 记住密码框
          :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
            color: $base-white !important;
          }
          :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
            background-color: #00a4cd;
            border-color: #00a4cd;
          }
          .loginButton {
            width: 320px;
            font-size: 18px;
            background: linear-gradient(to right, #00a4cd, #22c2dc);
            border: none;

            &:hover {
              background: #00a4cd;
              border: 1px solid #00a4cd;
            }
          }
          .caButton {
            width: 120px;
            font-size: 18px;
            background: linear-gradient(to right, #00a4cd, #22c2dc);
            border: none;

            &:hover {
              background: #00a4cd;
              border: 1px solid #00a4cd;
            }
          }
        }
      }
      .qrcodeDiv {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        .qrcodeOutTimeDiv {
          position: absolute;
          bottom: 10%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          .outTime {
            margin-left: 5px;
            margin-top: 4px;
            color: red;
          }
          .vxe-button {
            color: #fff;
            &:hover {
              color: green;
            }
          }
        }
      }
    }
  }

  #foot {
    height: 30%;
    color: #eee;
    font-size: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2%;
    span {
      margin-top: 10px;
      font-size: 15px;
    }
  }
}

// 验证码样式
.div-vcode {
  float: right;
  border: $border-1;
  height: 35px;
  cursor: pointer;
  width: 80px;
  img {
    width: 80px;
    height: 35px;
  }
}
::v-deep .qrcode {
  margin: 20%;
  img {
    width: 200px;
    height: 200px;
  }
}
</style>
